/*
 * Copyright 2009 Tran Nhut Trung.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.eclipse.core.databinding.observable.gwt.internal;


import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.gwt.internal.widgets.ScrollTable;
import org.eclipse.core.databinding.observable.gwt.internal.widgets.TableSection;

public class DataTableIndexObservableValue extends WidgetPropertyObservableValue {
  private ScrollTable table;
  private int selectedIndex;
  
  private ClickHandler clickHandler = new ClickHandler(){
    public void onClick(ClickEvent event) {
      TableSection.Cell cell = table.getBody().getCellForEvent(event);
      if (cell != null){
        selectedIndex = cell.getRowIndex();
        processUpdate(selectedIndex);
      }
    }
  };
  
  public DataTableIndexObservableValue(ScrollTable table) {
    this(Realm.getDefault(), table);
  }
  public DataTableIndexObservableValue(Realm realm, ScrollTable table) {
    super(realm, table, "selectedIndex");
    
    this.table = table;
    table.getBody().addClickHandler(clickHandler);
  }
  
  public Object doGetValue() {
    return selectedIndex;
  }

  public Object getValueType() {
    return Integer.class;
  }

  protected void doSetApprovedValue(Object value) {
    try {
      updating = true;
      styleRow(selectedIndex, false);
      selectedIndex = (Integer)value;
      styleRow(selectedIndex, true);
      
      oldValue = doGetValue();
    } finally {
      updating = false;
    }
  }
  
  private void styleRow(int row, boolean selected){
    if (row < 0){
      return;
    }
    TableSection.RowFormatter rowFormatter = table.getBody().getRowFormatter();
    
    if (selected){
      rowFormatter.addStyleName(row, "selected");
    }else{
      rowFormatter.removeStyleName(row, "selected");
    }
  }
}
